<template>
  <div class="health-record-container">
    <h2 class="health-record-title">记录健康数据</h2>
    
    <el-card shadow="hover" class="record-form-card">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="健康类型">
          <el-select v-model="formData.typeId" placeholder="请选择健康数据类型" @change="handleTypeChange">
            <el-option
              v-for="type in healthTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="记录日期">
          <el-date-picker
            v-model="formData.recordDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="记录时间">
          <el-time-picker
            v-model="formData.recordTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item :label="selectedType ? (selectedType.name + '数值') : '数值'" v-if="selectedType && selectedType.isNumeric">
          <el-input
            v-model="formData.value"
            :placeholder="`请输入${selectedType.name}数值${selectedType.unit ? '（' + selectedType.unit + '）' : ''}`"
            clearable
          >
            <template #append v-if="selectedType.unit">
              {{ selectedType.unit }}
            </template>
          </el-input>
          <div class="normal-range" v-if="selectedType.minValue !== null && selectedType.maxValue !== null">
            正常范围：{{ selectedType.minValue }} - {{ selectedType.maxValue }} {{ selectedType.unit }}
          </div>
        </el-form-item>
        
        <el-form-item :label="selectedType ? (selectedType.name + '内容') : '内容'" v-if="selectedType && !selectedType.isNumeric">
          <el-input
            v-model="formData.value"
            :placeholder="`请输入${selectedType.name}内容`"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="addRecord" :loading="submitting">
            保存记录
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 历史记录表格 -->
    <div class="record-history">
      <div class="history-header">
        <h3>历史记录</h3>
        <el-select 
          v-model="selectedTypeId" 
          placeholder="选择健康类型" 
          clearable 
          @change="handleFilterChange"
          style="width: 200px"
        >
          <el-option
            v-for="type in healthTypes"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          />
        </el-select>
      </div>
      
      <el-table
        :data="records"
        border
        style="width: 100%"
        v-loading="loadingRecords"
      >
        <el-table-column prop="recordDate" label="日期" width="120" />
        <el-table-column prop="recordTime" label="时间" width="120" />
        <el-table-column prop="typeName" label="类型" width="150" />
        <el-table-column label="数值" min-width="150">
          <template #default="scope">
            <span>{{ scope.row.recordValue }} {{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isAbnormal ? 'danger' : 'success'">
              {{ scope.row.isAbnormal ? '异常' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteHealthRecord(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container" v-if="pagination.total > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @current-change="handlePageChange"
        />
      </div>
      
      <el-empty description="暂无健康记录" v-if="records.length === 0 && !loadingRecords" />
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'HealthRecord',
  setup() {
    // 获取当前用户ID
    let userId = null
    const userInfoStr = localStorage.getItem('userInfo')
    const userStr = localStorage.getItem('user')
    
    if (userInfoStr) {
      try {
        userId = JSON.parse(userInfoStr).id
        console.log('从userInfo获取到用户ID:', userId)
      } catch (e) {
        console.error('解析userInfo失败:', e)
      }
    } else if (userStr) {
      try {
        userId = JSON.parse(userStr).id
        console.log('从user获取到用户ID:', userId)
      } catch (e) {
        console.error('解析user失败:', e)
      }
    }
    
    if (!userId) {
      // 如果都没有获取到，默认使用ID为8用于测试
      userId = 8
      console.log('未找到用户信息，使用默认ID:', userId)
    }
    
    // 表单数据
    const formData = reactive({
      userId: userId,
      typeId: '',
      value: '',
      recordDate: new Date().toISOString().split('T')[0], // 默认为今天
      recordTime: new Date().toTimeString().split(' ')[0].substring(0, 8), // 默认为当前时间
      notes: ''
    })

    // 健康类型列表
    const healthTypes = ref([])

    // 获取选中的健康类型
    const selectedType = computed(() => {
      return healthTypes.value.find(type => type.id === formData.typeId) || null
    })

    // 健康记录历史
    const records = ref([])
    const loadingRecords = ref(false)
    const selectedTypeId = ref('')
    const pagination = ref({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    const submitting = ref(false)

    // 获取健康记录类型
    const getHealthTypes = async () => {
      try {
        // 尝试从本地存储获取数据
        const localData = localStorage.getItem('health_types')
        if (localData) {
          healthTypes.value = JSON.parse(localData)
          console.log('从本地存储加载健康类型:', healthTypes.value)
          return
        }
        
        // 使用模拟数据
        loadDemoTypes()
        
        // 保存演示数据到本地存储
        localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
      } catch (error) {
        console.error('获取健康记录类型失败', error)
        // 加载演示数据
        loadDemoTypes()
        // 保存演示数据到本地存储
        localStorage.setItem('health_types', JSON.stringify(healthTypes.value))
      }
    }

    // 加载演示的健康类型数据
    const loadDemoTypes = () => {
      healthTypes.value = [
        { id: 1, name: '血压(收缩压)', unit: 'mmHg', isNumeric: true, minValue: 60, maxValue: 180, icon: 'iconfont icon-blood-pressure' },
        { id: 2, name: '血压(舒张压)', unit: 'mmHg', isNumeric: true, minValue: 40, maxValue: 120, icon: 'iconfont icon-blood-pressure' },
        { id: 3, name: '心率', unit: '次/分钟', isNumeric: true, minValue: 40, maxValue: 200, icon: 'iconfont icon-heart-rate' },
        { id: 4, name: '血糖(空腹)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 6.1, icon: 'iconfont icon-blood-glucose' },
        { id: 5, name: '血糖(餐后2小时)', unit: 'mmol/L', isNumeric: true, minValue: 3.9, maxValue: 7.8, icon: 'iconfont icon-blood-glucose' },
        { id: 6, name: '体重', unit: 'kg', isNumeric: true, minValue: 30, maxValue: 150, icon: 'iconfont icon-weight' },
        { id: 7, name: '体温', unit: '℃', isNumeric: true, minValue: 35, maxValue: 42, icon: 'iconfont icon-temperature' },
        { id: 8, name: '睡眠时间', unit: '小时', isNumeric: true, minValue: 0, maxValue: 24, icon: 'iconfont icon-sleep' },
        { id: 9, name: '用药记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-medication' },
        { id: 10, name: '饮食记录', unit: '', isNumeric: false, minValue: null, maxValue: null, icon: 'iconfont icon-diet' }
      ]
    }

    // 英文健康类型名称翻译为中文
    const translateTypeName = (engName) => {
      const typeMap = {
        'Blood Pressure (Systolic)': '血压(收缩压)',
        'Blood Pressure (Diastolic)': '血压(舒张压)',
        'Heart Rate': '心率',
        'Blood Glucose (Fasting)': '血糖(空腹)',
        'Blood Glucose (2h Postprandial)': '血糖(餐后2小时)',
        'Weight': '体重',
        'Body Temperature': '体温',
        'Sleep Duration': '睡眠时间',
        'Medication Record': '用药记录',
        'Dietary Record': '饮食记录'
      }
      return typeMap[engName] || engName
    }

    // 英文健康类型描述翻译为中文
    const translateTypeDescription = (engDesc) => {
      const descMap = {
        'Systolic blood pressure measurement': '收缩压测量',
        'Diastolic blood pressure measurement': '舒张压测量',
        'Heart rate measurement': '心率测量',
        'Fasting blood glucose level': '空腹血糖水平',
        'Blood glucose 2 hours after meal': '餐后2小时血糖水平',
        'Body weight measurement': '体重测量',
        'Body temperature measurement': '体温测量',
        'Hours of sleep per night': '每晚睡眠时间',
        'Daily medication intake records': '每日药物摄入记录',
        'Daily food intake records': '每日食物摄入记录'
      }
      return descMap[engDesc] || engDesc
    }

    // 类型变化时重置部分表单数据
    const handleTypeChange = () => {
      formData.value = ''
    }

    // 删除健康记录
    const deleteHealthRecord = (id) => {
      ElMessageBox.confirm('确定要删除这条健康记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 从本地存储获取健康记录
          let healthRecords = []
          const localData = localStorage.getItem(`health_records_${userId}`)
          if (localData) {
            healthRecords = JSON.parse(localData)
          }
          
          // 找到要删除的记录索引
          const recordIndex = healthRecords.findIndex(record => record.id === id)
          if (recordIndex >= 0) {
            // 删除记录
            healthRecords.splice(recordIndex, 1)
            
            // 保存更新后的记录
            localStorage.setItem(`health_records_${userId}`, JSON.stringify(healthRecords))
            
            ElMessage.success('删除成功')
            getRecords()
            
            // 更新健康总览数据
            updateHealthOverviewAfterDelete(id)
          } else {
            ElMessage.error('记录不存在')
          }
        } catch (error) {
          console.error('删除健康记录失败', error)
          ElMessage.error('删除健康记录失败')
        }
      }).catch(() => {})
    }

    // 更新健康总览数据
    const updateHealthOverviewAfterDelete = (deletedId) => {
      // 从本地存储获取所有健康记录
      let healthRecords = []
      const localData = localStorage.getItem(`health_records_${userId}`)
      if (localData) {
        healthRecords = JSON.parse(localData)
      }
      
      // 从本地存储获取健康总览数据
      let overviewData = []
      const overviewLocalData = localStorage.getItem(`health_overview_${userId}`)
      if (overviewLocalData) {
        overviewData = JSON.parse(overviewLocalData)
      }
      
      // 更新每种类型的最新记录
      for (let i = 0; i < overviewData.length; i++) {
        const typeId = overviewData[i].typeId
        // 查找该类型的最新记录
        const latestRecord = healthRecords
          .filter(record => record.typeId === typeId)
          .sort((a, b) => {
            const dateA = new Date(`${a.recordDate} ${a.recordTime}`)
            const dateB = new Date(`${b.recordDate} ${b.recordTime}`)
            return dateB - dateA
          })[0]
        
        if (latestRecord) {
          // 更新最新记录
          const selectedType = healthTypes.value.find(t => t.id === typeId)
          overviewData[i] = {
            typeId: typeId,
            typeName: selectedType.name,
            lastValue: latestRecord.recordValue,
            unit: selectedType.unit,
            lastDate: `${latestRecord.recordDate} ${latestRecord.recordTime}`,
            isAbnormal: latestRecord.isAbnormal
          }
        } else {
          // 如果该类型没有记录了，则从总览中移除
          overviewData.splice(i, 1)
          i--
        }
      }
      
      // 保存更新后的总览数据
      localStorage.setItem(`health_overview_${userId}`, JSON.stringify(overviewData))
    }

    // 添加健康记录
    const addRecord = async () => {
      if (!formData.typeId) {
        ElMessage.warning('请选择健康记录类型')
        return
      }
      
      const selectedType = healthTypes.value.find(t => t.id === formData.typeId)
      
      // 检查数值健康记录是否符合范围
      if (selectedType.isNumeric) {
        if (!formData.value) {
          ElMessage.warning(`请输入${selectedType.name}数值`)
          return
        }
        
        const numValue = parseFloat(formData.value)
        if (isNaN(numValue)) {
          ElMessage.warning(`${selectedType.name}数值必须是数字`)
          return
        }
        
        if (selectedType.minValue !== null && numValue < selectedType.minValue) {
          ElMessage.warning(`${selectedType.name}数值不能小于${selectedType.minValue}${selectedType.unit}`)
          return
        }
        
        if (selectedType.maxValue !== null && numValue > selectedType.maxValue) {
          ElMessage.warning(`${selectedType.name}数值不能大于${selectedType.maxValue}${selectedType.unit}`)
          return
        }
      } else if (!formData.value && !formData.notes) {
        // 非数值类型记录，至少要有记录内容或备注
        ElMessage.warning(`请输入${selectedType.name}内容或备注`)
        return
      }
      
      try {
        submitting.value = true
        
        // 从本地存储获取现有健康记录
        let healthRecords = []
        const localData = localStorage.getItem(`health_records_${userId}`)
        if (localData) {
          healthRecords = JSON.parse(localData)
        }
        
        // 准备新记录
        const isAbnormal = selectedType.isNumeric && 
          (parseFloat(formData.value) < selectedType.minValue || 
           parseFloat(formData.value) > selectedType.maxValue)
        
        const newRecord = {
          id: Date.now(), // 使用时间戳作为唯一ID
          userId: userId,
          typeId: formData.typeId,
          recordValue: formData.value,
          recordDate: formData.recordDate,
          recordTime: formData.recordTime,
          notes: formData.notes,
          typeName: selectedType.name,
          unit: selectedType.unit,
          isAbnormal: isAbnormal,
          createTime: new Date().toISOString()
        }
        
        // 添加新记录
        healthRecords.unshift(newRecord)
        
        // 保存到本地存储
        localStorage.setItem(`health_records_${userId}`, JSON.stringify(healthRecords))
        
        // 更新健康总览数据
        updateHealthOverview(newRecord)
        
        ElMessage.success('健康记录添加成功')
        // 重置表单
        resetForm()
        // 刷新记录列表
        getRecords()
      } catch (error) {
        console.error('添加健康记录失败', error)
        ElMessage.error('添加健康记录失败')
      } finally {
        submitting.value = false
      }
    }

    // 更新健康总览数据
    const updateHealthOverview = (newRecord) => {
      // 从本地存储获取健康总览数据
      let overviewData = []
      const localData = localStorage.getItem(`health_overview_${userId}`)
      if (localData) {
        overviewData = JSON.parse(localData)
      }
      
      // 查找是否已存在该类型的记录
      const existingIndex = overviewData.findIndex(item => item.typeId === newRecord.typeId)
      
      const selectedType = healthTypes.value.find(t => t.id === newRecord.typeId)
      const overviewItem = {
        typeId: newRecord.typeId,
        typeName: selectedType.name,
        lastValue: newRecord.recordValue,
        unit: selectedType.unit,
        lastDate: `${newRecord.recordDate} ${newRecord.recordTime}`,
        isAbnormal: newRecord.isAbnormal
      }
      
      if (existingIndex >= 0) {
        // 更新现有记录
        overviewData[existingIndex] = overviewItem
      } else {
        // 添加新记录
        overviewData.push(overviewItem)
      }
      
      // 保存更新后的总览数据
      localStorage.setItem(`health_overview_${userId}`, JSON.stringify(overviewData))
    }

    // 重置表单
    const resetForm = () => {
      formData.typeId = ''
      formData.value = ''
      formData.notes = ''
      formData.recordDate = new Date().toISOString().split('T')[0]
      formData.recordTime = new Date().toTimeString().split(' ')[0].substring(0, 8)
    }

    // 获取健康记录历史
    const getRecords = async () => {
      if (!userId) return
      
      loadingRecords.value = true
      try {
        // 从本地存储获取健康记录
        let healthRecords = []
        const localData = localStorage.getItem(`health_records_${userId}`)
        if (localData) {
          healthRecords = JSON.parse(localData)
        }
        
        // 应用筛选
        if (selectedTypeId.value) {
          healthRecords = healthRecords.filter(record => record.typeId === selectedTypeId.value)
        }
        
        // 应用分页
        const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
        const end = start + pagination.value.pageSize
        records.value = healthRecords.slice(start, end)
        pagination.value.total = healthRecords.length
      } catch (error) {
        console.error('获取健康记录失败', error)
        records.value = []
        pagination.value.total = 0
      } finally {
        loadingRecords.value = false
      }
    }

    // 处理页码变化
    const handlePageChange = (page) => {
      pagination.value.currentPage = page
      getRecords()
    }

    // 处理筛选变化
    const handleFilterChange = () => {
      pagination.value.currentPage = 1
      getRecords()
    }

    // 初始化
    onMounted(() => {
      getHealthTypes()
      getRecords()
    })

    return {
      formData,
      healthTypes,
      selectedType,
      records,
      loadingRecords,
      selectedTypeId,
      pagination,
      submitting,
      getHealthTypes,
      getRecords,
      handleTypeChange,
      deleteHealthRecord,
      addRecord,
      resetForm,
      handlePageChange,
      handleFilterChange
    }
  }
}
</script>

<style scoped>
.health-record-container {
  padding: 20px;
}

.health-record-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-weight: 500;
}

.record-form-card {
  margin-bottom: 30px;
}

.normal-range {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.record-history {
  margin-top: 40px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style> 